package dinner.web.eat;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import dinner.web.Eat;
import dinner.web.ReportLine;
import dinner.web.libs.IOUtils;

public class ReportIO {

	public static void closeUser(String logined) {
		File path = new File(IO.getDBForCurrentDate(), "closed.db");
		List<String> closed = IOUtils.read(path, String.class);
		if (closed == null) {
			closed = new ArrayList<String>();
		}
		closed.add(logined);
		IOUtils.write(closed, path);
	}

	public static List<ReportLine> getReport() {
		File path = new File(IO.getDBForCurrentDate());
		String[] names = path.list(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".db") && !name.equals("menu.db") && !name.equals("closed.db");
			}
		});
		{
			File pathClosed = new File(IO.getDBForCurrentDate(), "closed.db");
			List<String> closed = IOUtils.read(pathClosed, String.class);
			if (closed == null) {
				closed = new ArrayList<String>();
			}
			closed.addAll(Arrays.asList(names));
			IOUtils.write(closed, pathClosed);
		}
		Report report = new Report();
		for (String userName : names) {
			File userAnswer = new File(path, userName);
			List<Eat> zakaz = IOUtils.read(userAnswer, Eat.class);
			if (zakaz != null) {
				for (Eat e : zakaz) {
					if (e.getPieces() > 0) {
						report.add(ReportLine.createLine(e, userName.substring(0, userName.length() - 3)));
					}
				}
			}
		}
		return new ArrayList<ReportLine>(report);
	}

	/**
	 * 
	 * @param logined
	 * @return true if user not finish make the dinner
	 */
	public static boolean userNotClosed(String logined) {
		File path = new File(IO.getDBForCurrentDate(), "closed.db");
		List<String> closed = IOUtils.read(path, String.class);
		if (closed == null) {
			closed = new ArrayList<String>();
		}
		return !closed.contains(logined);
	}

}
